import { useCallback } from 'react';
import { useAppSelector, useAppDispatch } from './redux';
import { loginUser, registerUser, logoutUser, clearError } from '../store/authSlice';
import { useNavigate } from 'react-router-dom';
import socketService from '../services/socketService';

// 自定义Hook：处理用户认证
export const useAuth = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const { user, token, isLoading, error, isAuthenticated } = useAppSelector(state => state.auth);

  // 登录
  const login = useCallback(async (email: string, password: string) => {
    try {
      const result = await dispatch(loginUser({ email, password })).unwrap();
      
      // 登录成功后，建立Socket连接
      if (result.token) {
        socketService.connect(result.token);
      }
      
      // 导航到游戏大厅
      navigate('/lobby');
      
      return result;
    } catch (error) {
      console.error('Login failed:', error);
      throw error;
    }
  }, [dispatch, navigate]);

  // 注册
  const register = useCallback(async (username: string, email: string, password: string) => {
    try {
      const result = await dispatch(registerUser({ username, email, password })).unwrap();
      
      // 注册成功后，建立Socket连接
      if (result.token) {
        socketService.connect(result.token);
      }
      
      // 导航到游戏大厅
      navigate('/lobby');
      
      return result;
    } catch (error) {
      console.error('Registration failed:', error);
      throw error;
    }
  }, [dispatch, navigate]);

  // 登出
  const logout = useCallback(async () => {
    try {
      await dispatch(logoutUser()).unwrap();
      
      // 断开Socket连接
      socketService.disconnect();
      
      // 导航到首页
      navigate('/');
    } catch (error) {
      console.error('Logout failed:', error);
      // 即使登出失败，也断开Socket连接并导航到首页
      socketService.disconnect();
      navigate('/');
    }
  }, [dispatch, navigate]);

  // 清除错误信息
  const clearAuthError = useCallback(() => {
    dispatch(clearError());
  }, [dispatch]);

  return {
    user,
    token,
    isLoading,
    error,
    isAuthenticated,
    login,
    register,
    logout,
    clearAuthError,
  };
};